# -*- coding: utf-8 -*-
import random
import requests
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import json
from conifig import APPID, CROPID, ENTERPRISEID, REQUEST_HOST, dby_url, account, accountKey, num, city, connect, cursor
from Logs.log import log1


class SouGouWeiXinSpider:
    def __init__(self):
        self.url = "https://weixin.sogou.com/"

    def get_proxy(self, wait):
        params = {
            "account": account,
            "accountKey": accountKey,
            "num": num,
            "cityId": city
        }
        try:
            time.sleep(wait)
            resp_js = requests.get(dby_url, params=params)
            resp = json.loads(resp_js.text)
            if resp["code"] == "200":
                pro_ip = resp["data"][0]["ip"]
                pro_port = resp["data"][0]["port"]
                ip = '{}:{}'.format(pro_ip, pro_port)
                proxies = {
                    "http": "http://" + ip,
                }
                resp = requests.get(self.url, proxies=proxies)
                s_code = resp.status_code
                if s_code == 200:
                    return ip
                else:
                    return
        except Exception as e:
            log1.error("获取代理IP异常: {}".format(e))
            return

    def user_agent(self):
        first_num = random.randint(55, 62)
        third_num = random.randint(0, 3200)
        fourth_num = random.randint(0, 140)
        os_type = [
            '(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
            '(Macintosh; Intel Mac OS X 10_12_6)'
        ]
        chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)
        ua = ' '.join(['Mozilla/5.0', random.choice(os_type), 'AppleWebKit/537.36',
                       '(KHTML, like Gecko)', chrome_version, 'Safari/537.36'])
        return ua

    def options(self, ip=None):
        chromeOptions = webdriver.ChromeOptions()
        # chromeOptions.add_argument(('--proxy-server=http://' + ip))
        chromeOptions.add_argument('user-agent=' + self.user_agent())
        chromeOptions.add_argument('--no-sandbox')
        chromeOptions.add_argument('--disable-gpu')
        chromeOptions.add_experimental_option('excludeSwitches', ['enable-automation'])
        chromeOptions.add_argument('blink-settings=imagesEnabled=false')
        chromeOptions.add_argument("--headless")
        return chromeOptions

    def request_url(self, chromeOptions):
        driver = webdriver.Chrome(options=chromeOptions)
        driver.get(self.url)
        return driver

    def web_driver(self, driver, name):
        url = ""
        try:
            query_input = WebDriverWait(driver, 5).until(
                lambda driver: driver.find_element_by_xpath('//*[@id="query"]'))
            query_input.clear()
            query_input.send_keys(name)
            driver.find_element_by_xpath('//div[@class="header-box"]//input[@class="swz2"]').click()
            time.sleep(1)
            try:
                WebDriverWait(driver, 5).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="sogou_vr_11002301_box_0"]//a[@uigs="account_article_0"]'))).click()
                time.sleep(3)
                driver.switch_to.window(driver.window_handles[1])
                url = driver.current_url
                print(name, url)

            except:
                log1.info("{}无最新文章".format(name))
        except Exception as e:
            log1.error("{}爬取异常: {}".format(name, e))
        driver.quit()
        return url

    def start_requests(self, row, wait=None):
        # ip = self.get_proxy(wait)
        # if not ip:
        #     log1.info("获取代理IP失败/IP失效")
        #     return
        for net in row:
            chromeOptions = self.options()
            driver = self.request_url(chromeOptions)
            domain = net[0]
            self.web_driver(driver, domain)


if __name__ == '__main__':
    sgwx = SouGouWeiXinSpider()
    row = ["深圳房产资讯", "深圳房产平台"]
    sgwx.start_requests(row)
